//
//  YHLocationManager.swift
//  FuweiCloud
//
//  Created by michael on 2024/7/4.
//

import CoreLocation
import Foundation
import NetworkExtension
import SystemConfiguration.CaptiveNetwork

public class YHLocationManager: NSObject, CLLocationManagerDelegate {
  @objc public static let shared = YHLocationManager()

  private let locationManager = CLLocationManager()
  private var confirmBlock: YHVoidBlock? = nil

  @objc public func requestLocation(_ confirmBlock: YHVoidBlock? = nil) -> Bool {
    var title: String? = nil
    let status = if #available(iOS 14.0, *) {
      locationManager.authorizationStatus
    } else {
      CLLocationManager.authorizationStatus()
    }
    if status == .notDetermined {
      locationManager.requestWhenInUseAuthorization()
      locationManager.delegate = self
      self.confirmBlock = confirmBlock
      return false
    }
    if #available(iOS 13.0, *) {
      if status == .restricted || status == .denied {
        title = "We need to access your location permission to get WiFi information on iOS 13.0 and above. WiFi information is used to configure the network for your IoT device. We will not use your location information for other unauthorized purposes".local
      }
    }
    if #available(iOS 14.0, *) {
      if locationManager.accuracyAuthorization == .reducedAccuracy {
        title = "We need to access your precise location permission so that we can get WiFi information on iOS14.0 and above systems. WiFi information is used to configure the network for your IoT device".local
      }
    }
    if let title {
      YHAlertPopView.pop(properties: [
        .header: title,
        .rightButton: "Setting".local
      ]) { userInfo in
        if userInfo == nil { return }
        YHAppSettingURLHelper.gotoURL(.appSetting)
      }
    }
    return title == nil
  }

  @objc public func getWiFiName(maxRetries: Int = 3, completion: @escaping (String?) -> Void) {
    // 1. 定義內嵌的 "worker" 函數
    // 這個函數捕獲了外層的 completion 和 maxRetries 參數
    func attempt(currentAttempt: Int) {
      // 2. 統ㄧ的結果處理邏輯
      let handleResult = { (ssid: String?) in
        // 成功獲取到 SSID
        if let ssid = ssid, !ssid.isEmpty {
          print("已獲取到SSID: \(ssid)")
          completion(ssid)
          return
        }

        // 檢查是否可以重試
        if currentAttempt < maxRetries {
          let nextAttempt = currentAttempt + 1
          print("獲取 SSID 失敗，將在 1 秒後進行第 \(nextAttempt) 次嘗試 (共 \(maxRetries) 次)...")

          DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
            // 內嵌函數遞歸調用自身
            attempt(currentAttempt: nextAttempt)
          }
        } else {
          // 所有重試均失敗
          print("已達到最大重試次數 (\(maxRetries))，獲取 SSID 失敗。")
          completion(nil)
        }
      }

      // 3. 根據系統版本執行不同的獲取邏輯
      if #available(iOS 14.0, *) {
        NEHotspotNetwork.fetchCurrent { network in
          handleResult(network?.ssid)
        }
      } else {
        var ssid: String?
        if let interfaces = CNCopySupportedInterfaces() as? [String] {
          for interface in interfaces {
            if let interfaceInfo = CNCopyCurrentNetworkInfo(interface as CFString) as? [String: AnyObject] {
              ssid = interfaceInfo[kCNNetworkInfoKeySSID as String] as? String
              if ssid != nil { break }
            }
          }
        }
        handleResult(ssid)
      }
    }

    // 4. 啟動第一次嘗試
    attempt(currentAttempt: 1)
  }

  @available(iOS 14.0, *)
  public func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {
    let status = manager.authorizationStatus
    if status == .authorizedWhenInUse && manager.accuracyAuthorization == .fullAccuracy {
      confirmBlock?()
      confirmBlock = nil
    }
  }

  public func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
    if status == .authorizedWhenInUse {
      confirmBlock?()
      confirmBlock = nil
    }
  }
}
